#--------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------ Lea Portmann ------------------------------------------------#
#------------------------------------------------------ October 2021 ------------------------------------------------#
#--------- What Makes a Successful Candidate? Political Experience and Low-Information Cues in Elections ------------#
#---------------------------------------------------- Competence Experiment -----------------------------------------#
#--------------------------------------------------------------------------------------------------------------------#

# ------------------------------------------------------------ Read data

library(Hmisc)
library(dplyr)
library(texreg)
library(effects)
library(margins)
library(ggplot2)
library(gridExtra)
library(texreg)
library(viridis)
library(gridExtra)
library(plyr)

rm(list=ls())
load(".../.../d_exp1.RData")
d <- d_exp1

# ------------------------------------------------------------ Build variables demographic characteristics

names(d)
table(d$Finished)
table(d$Status)
table(d$DistributionChannel)
table(d$UserLanguage)

# Gender

describe(d$GENDER)
table(d$GENDER)
d$gender <- mapvalues(d$GENDER, from = c("Männlich", "Weiblich"), to = c("Male", "Female"))
table(d$gender)

# Political interest

describe(d$POLINT)
table(d$POLINT)

# Ideology

table(d$IDEOL)

#Age

describe(d$AGE)
table(d$AGE)

d$age <- factor(d$AGE, 
                labels= c("18-34 years", "35-54 years", "55-74 years", "Older than 74 years"))
table(d$age)

#Education

table(d$EDUC)
describe(d$EDUC)
table(d$EDUC_13_TEXT)

d$educ <- mapvalues(d$EDUC, from = c("Andere", "Keine Schulbildung","Primarschule", 
"Sekundarschule", "Anlehre (mit Anlehrvertrag)", 
"Berufslehre oder Berufsschule", "Diplommittelschule oder allgemeinbildende Schule", 
"Handelsschule oder Handelsdiplom", "Berufsmatura", "Maturitätsschule, Gymnasium, Seminar", 
"Höhere Berufsbildung mit eidg. Fachausweis oder eidg. Diplom oder Meisterdiplom", 
"Höhere Fachschule (HF) für Technik, Wirtschaft (HKG, HWV, HFG, HFS, Ingenieurschule), Sozialarbeit o.ä.", 
"Fachhochschule (FH) oder Pädagogische Hochschule (PH)", "Universität oder ETH"), 
to = c("low", "low", "low", "low", "low", 
"medium", "medium", "medium", "medium", "medium", "medium",
"high", "high", "high"))
describe(d$educ)
table(d$EDUC)

#Income

describe(d$INCOME)


# -------------------------------------------------------------------------- Build experimental variables

# ----- Generally which experimental manipulation

names(d)

#rename columns

names(d)[27] <- "T1"
names(d)[28] <- "T2"
names(d)[29] <- "T3"
names(d)[30] <- "T4"

#Build factor variable

d$exp[d$T1==1] <- 1
d$exp[d$T2==1] <- 2
d$exp[d$T3==1] <- 3
d$exp[d$T4==1] <- 4

d$exp <- factor(d$exp, 
levels = c(1, 2, 3, 4), 
labels = c("No political office and no competence", 
"Local political office and no competence", 
"No political office and competence", 
"Local political office and comptence"))

table(d$exp)
describe(d$exp)

# ----- Treatment political office

d$treat <- ifelse(d$exp=="No political office and no competence" | d$exp=="No political office and competence", 0, 
ifelse(d$exp=="Local political office and no competence" | d$exp=="Local political office and comptence", 1, NA))
table(d$treat, d$exp)
describe(d$treat)

# ----- Moderator competence

d$mod <- ifelse(d$exp=="No political office and no competence" | d$exp=="Local political office and no competence", 0, ifelse( 
d$exp=="No political office and competence" | d$exp=="Local political office and comptence", 1, NA))
table(d$mod)
describe(d$mod)

table(d$mod, d$exp)

# ---------- Exclude respondents who did not go trough the experiment

d <- d %>% filter(!is.na(exp))

# -------------------------------------------------------------------------- Manipulation check

# ------ Prepare data

d$MANP_Huber_qualified <- as.numeric(as.character(d$MAN_CHECK_Huber_1))
d$MANP_Huber_competent <- as.numeric(as.character(d$MAN_CHECK_Huber_2))
d$MANP_Schmid_qualified <- as.numeric(as.character(d$MAN_CHECK_Schmid_1))
d$MANP_Schmid_competent <- as.numeric(as.character(d$MAN_CHECK_Schmid_2))

# ------ Difference

d$diff_qualified <- d$MANP_Huber_qualified - d$MANP_Schmid_qualified
d$diff_competent <- d$MANP_Huber_competent - d$MANP_Schmid_competent
table(d$diff_qualified)
hist(d$diff_qualified)
table(d$diff_competent)
hist(d$diff_competent)

# Competence manipulation

m1_mc_mod <- lm(diff_qualified ~ mod, data = d)
summary(m1_mc_mod)
m2_mc_mod <- lm(diff_competent ~ mod, data = d)
summary(m2_mc_mod)

# Political office manipulation

m1_mc_treat <- lm(diff_qualified ~ treat, data = d)
summary(m1_mc_treat)
m2_mc_treat <- lm(diff_competent ~ treat, data = d)
summary(m2_mc_treat)


# ------ Table

custom.name.1 <- c("Intercept", "Competence treatment",
"Political Experience information")

texreg(list(m1_mc_mod, m1_mc_treat), booktabs=TRUE,
#custom.coef.names = custom.name.1,
caption="Manipulation check",
caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))


# ------ Table of means

d_mc_mod <- d %>% 
filter(!is.na(diff_competent)) %>%
dplyr::group_by(mod) %>% 
dplyr::summarize(mean = mean(diff_competent))
  
d_mc_treat <- d %>% 
filter(!is.na(diff_competent)) %>%
dplyr::group_by(treat) %>% 
dplyr::summarize(mean = mean(diff_competent))


# -------------------------------------------------------------------------- Models

# ----- Prepare variables

d$Experience <- factor(d$treat, 
levels = c(0, 1), 
labels = c("No Political experience", "Political experience"))

d$mod <- factor(d$mod, 
levels = c(0, 1), 
labels = c("No competence description", "Competence description"))

d$DV_V1 <- ifelse(d$DV_2=="Daniel Huber", 1, ifelse(d$DV_2=="Andreas Schmid" | d$DV_2=="Ich weiss nicht.", 0, NA))
d$DV_V1 <- as.numeric(d$DV_V1)
table(d$DV_V1, d$DV_2)
table(d$DV_V1, d$exp)
describe(d$DV_V1)

d$DV_V2 <- ifelse(d$DV_2=="Daniel Huber", 1, ifelse(d$DV_2=="Andreas Schmid", 0, NA))
d$DV_V2 <- as.numeric(d$DV_V2)
table(d$DV_V2, d$DV_2)

d$DV_V3 <- ifelse(d$DV_2=="Daniel Huber", 1, ifelse(d$DV_2=="Andreas Schmid", -1, ifelse(d$DV_2=="Ich weiss nicht.", 0, NA)))
d$DV_V3 <- as.numeric(d$DV_V3)
table(d$DV_2, d$DV_V3)

# ------ Main models

m1_1_logit <- glm(DV_V1 ~ Experience, data = d, family = "binomial")
m2_1_logit <- glm(DV_V1 ~ mod, data = d, family = "binomial")
m3_1_logit <- glm(DV_V1 ~ Experience*mod, data = d, family = "binomial")

m1_1 <- lm(DV_V1 ~ Experience, data = d)
m2_1 <- lm(DV_V1 ~ mod, data = d)
m3_1 <- lm(DV_V1 ~ Experience*mod, data = d)

# ---------------- Figures

ef <- effect("Experience:mod", m3_1)
summary(ef)
ef <- as.data.frame(ef)
colors = c("grey50", "black")
mod_pred <- ggplot(ef, aes(mod, fit, color=Experience, fill=Experience)) + geom_point(size=2) + 
  geom_errorbar(aes(ymin=lower, ymax=upper), width=0.3, size=1) + 
  theme_bw(base_size=12) +
  theme_bw() + labs(x="", y="Likelihood of preferring Daniel Huber", title="B") +
  scale_colour_manual(values = colors, aesthetics = c("colour", "fill")) + 
  guides(fill=FALSE) + coord_flip() +
  #theme(legend.position="none") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
  theme(plot.title = element_text(size=11)); mod_pred

(marg1 <- margins(m3_1))
d_p_marg <- summary(margins(m3_1, at = list(mod = c("No competence description", "Competence description")), variables = "Experience"))

colors_1 <- c("black", "black")

mod_eff <- ggplot(d_p_marg, aes(x = mod, ymin=lower, ymax = upper,
color=Experience)) + geom_errorbar(color=c("black", "black"), width=0.3, size=1, 
position=position_dodge(.5)) + 
geom_point(aes(x=mod, y=AME, color=Experience), color=colors_1, size=2) +
#scale_y_continuous(limits=c(0, 1)) +
coord_flip() +
labs(x="", y="Effect of political experience", title="A", color = "Political experience") + theme_bw() +
scale_x_discrete(limits = rev(levels(d_p_marg$mod))) + 
geom_hline(yintercept=0, linetype="dashed", size=1)  +
scale_fill_manual(values=colors_1) + theme(legend.position="right") 

mod_exp_comb <- grid.arrange(mod_eff, mod_pred,  
                             ncol=2, nrow = 1,
                             widths = c(2, 2)); mod_exp_comb

# --- Tables

custom.name.1 <- c("Intercept", 
                   "Political Experience information", 
                   "Competence treatment", 
                   "Political Experience x Competence treatment")


texreg(list(m3_1), booktabs=TRUE,
       custom.coef.names = custom.name.1,
       caption="Likelihood of preferring Daniel over Andreas following political experience and competence treatments (linear model)",
       caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

texreg(list(m3_1_logit), booktabs=TRUE,
       custom.coef.names = custom.name.1,
       caption="Likelihood of preferring Daniel over Andreas following political experience and competence treatments (logit model)",
       caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

# ------ Alternative specifications dependent variable

m1_2 <- glm(DV_V2 ~ Experience, data = d, family = "binomial")
summary(m1_2)
m2_2 <- glm(DV_V2 ~ mod, data = d, family = "binomial")
summary(m2_2)
m3_2 <- glm(DV_V2~ Experience*mod, data = d, family = "binomial")
summary(m3_2)

table(d$exp, d$DV_2)

m1_3 <- lm(DV_V3 ~ Experience, data = d)
summary(m1_3)
m2_3 <- lm(DV_V3 ~ mod, data = d)
summary(m2_3)
m3_3 <- lm(DV_V3 ~ Experience*mod, data = d)
summary(m3_3)

# --- Table

texreg(list(m3_2, m3_3), booktabs=TRUE,
custom.coef.names = custom.name.1,
caption="Likelihood of preferring Daniel over Andreas following political experience and competence treatments, alternative specifications dependent variable",
caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

# ------ Models including covariates

m1_4 <- lm(DV_V1 ~ Experience + educ + gender + age, data = d)
m2_4 <- lm(DV_V1 ~ mod + educ + gender + age, data = d)
m3_4 <- lm(DV_V1 ~ Experience*mod+  educ + gender + age, data = d)
summary(m3_4)

# --- Table

custom.name.1 <- c("Intercept", 
                   "Political Experience information", 
                   "Competence treatment", 
                   "Education: low", "Education: medium", 
                   "Gender: Male", 
                   "Age: 35-54 years", "Age: 55-74 years", "Age: Older than 74 years",
                   "Political Experience x Competence treatment")


texreg(list(m3_4), booktabs=TRUE,
       custom.coef.names = custom.name.1,
       caption="Likelihood of preferring Daniel over Andreas following political experience and competence treatments",
       caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

# ----------------- Balance regarding pre-treatment variables

# --- Figure

#Education

d_balance_educ <- d %>% 
dplyr::filter(!is.na(educ)) %>% 
dplyr::group_by(exp, educ) %>%
dplyr::summarize(n = n()) %>%
dplyr::mutate(freq = (n / sum(n))*100)


balance_education <- ggplot(d_balance_educ, aes(x=exp, y=freq, fill=educ)) +
  geom_bar(stat = "identity") +
  #geom_text(aes(label=n, color=exp), vjust = -0.5) +
  scale_y_continuous("Proportion", limits=c(0,100)) +
  ggtitle("Balance for education") +
  theme(plot.title = element_text(size=12, hjust = 0.5)) + 
  scale_fill_viridis(discrete = TRUE) +
  theme_bw() + coord_flip() +
  scale_x_discrete(limits = rev(levels(d_balance_educ$exp))) + 
  theme(axis.title.x=element_blank()) + theme(axis.title.y=element_blank()) + labs(fill = "Education")

#Gender

d_balance_gender <- d %>% 
  dplyr::filter(!is.na(gender)) %>% 
  dplyr::group_by(exp, gender) %>%
  dplyr::summarize(n = n()) %>%
  dplyr::mutate(freq = (n / sum(n))*100)

balance_gender <- ggplot(d_balance_gender, aes(x=exp, y=freq, fill=gender)) +
  geom_bar(stat = "identity") +
  #geom_text(aes(label=n, color=exp), vjust = -0.5) +
  scale_y_continuous("Proportion", limits=c(0,100)) +
  ggtitle("Balance for gender") +
  theme(plot.title = element_text(size=12, hjust = 0.5)) + 
  scale_fill_viridis(discrete = TRUE) +
  theme_bw() + coord_flip() +
  scale_x_discrete(limits = rev(levels(d_balance_gender$exp))) + 
  theme(axis.title.x=element_blank()) + theme(axis.title.y=element_blank()) + labs(fill = "Gender")

#Age

d_balance_age <- d %>% 
  dplyr::filter(!is.na(age)) %>% 
  dplyr::group_by(exp, age) %>%
  dplyr::summarize(n = n()) %>%
  dplyr::mutate(freq = (n / sum(n))*100)

balance_age <- ggplot(d_balance_age, aes(x=exp, y=freq, fill=age)) +
  geom_bar(stat = "identity") +
  #geom_text(aes(label=n, color=exp), vjust = -0.5) +
  scale_y_continuous("Proportion", limits=c(0,100)) +
  ggtitle("Balance for age") +
  theme(plot.title = element_text(size=12, hjust = 0.5)) + 
  scale_fill_viridis(discrete = TRUE) +
  theme_bw() + coord_flip() +
  scale_x_discrete(limits = rev(levels(d_balance_age$exp))) + 
  theme(axis.title.x=element_blank()) + theme(axis.title.y=element_blank()) + labs(fill = "Age")

balance <- grid.arrange(balance_gender, balance_age, balance_education,
ncol=1, nrow = 3); balance

# --- Table

d %>% select(gender, exp, age, educ) %>% 
vtable::sumtable(vars = c("gender", "age", "educ"), group="exp", group.test=TRUE, out="latex")




